/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */

package vip.xiaonuo.biz.modular.nccAi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import vip.xiaonuo.biz.modular.file.service.BizFileManagerService;
import vip.xiaonuo.biz.modular.nccAi.entity.BankReceiptInfo;
import vip.xiaonuo.biz.modular.nccAi.entity.BizNccCode;
import vip.xiaonuo.biz.modular.nccAi.entity.ConCustomerInfo;
import vip.xiaonuo.biz.modular.nccAi.param.*;
import vip.xiaonuo.biz.modular.nccAi.service.BizNccCodeService;
import vip.xiaonuo.biz.modular.nccAi.service.ConCustomerInfoService;
import vip.xiaonuo.biz.modular.nccAi.util.*;
import vip.xiaonuo.biz.modular.nccAi.util.nccReq.*;
import vip.xiaonuo.biz.modular.pay.entity.BizPayAccount;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.nccAi.entity.BizAiNcc;
import vip.xiaonuo.biz.modular.nccAi.mapper.BizAiNccMapper;
import vip.xiaonuo.biz.modular.nccAi.service.BizAiNccService;
import vip.xiaonuo.common.util.CommonDownloadUtil;
import vip.xiaonuo.dev.api.DevFileApi;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * biz_ai_nccService接口实现类
 *
 * @author xsl
 * @date  2025/04/12 20:32
 **/
@Slf4j
@Service
public class BizAiNccServiceImpl extends ServiceImpl<BizAiNccMapper, BizAiNcc> implements BizAiNccService {

    @Resource
    ConCustomerInfoService conCustomerInfoService;

    @Resource
    BizNccCodeService bizNccCodeService;

    @Resource
    DevFileApi fileApi;

    @Resource
    BizFileManagerService bizFileManagerService;

    @Override
    public Page<BizAiNcc> page(BizAiNccPageParam bizAiNccPageParam) {
        QueryWrapper<BizAiNcc> queryWrapper = new QueryWrapper<BizAiNcc>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizAiNccPageParam.getCustomer())) {
            queryWrapper.lambda().eq(BizAiNcc::getConNum, bizAiNccPageParam.getCustomer());
        }
        if(ObjectUtil.isNotEmpty(bizAiNccPageParam.getOrderDate())) {
            queryWrapper.lambda().eq(BizAiNcc::getExecuteId, bizAiNccPageParam.getOrderDate());
        }

        if(ObjectUtil.isAllNotEmpty(bizAiNccPageParam.getSortField(), bizAiNccPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizAiNccPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizAiNccPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizAiNccPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizAiNcc::getId);
        }

        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    /**
     * 创建ncc单据（异步开启，结束后同步数据库状态）
     * @param bizAiNccAddParam
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizAiNccAddParam bizAiNccAddParam) {
        // 获取文件上传内容
        List<String> fileList = bizAiNccAddParam.getNccFileList();
        // 调用coze平台Api
        CozeClient cozeClient = new CozeClient();
        Map<String, Object> param = new HashMap<>();
        param.put("fileList", fileList);
        String executeId =  cozeClient.runWorkFlowAsync("7481464889277054985", param);
        BizAiNcc bizAiNcc = BeanUtil.toBean(bizAiNccAddParam, BizAiNcc.class);
        bizAiNcc.setFileSize(fileList.size());
        bizAiNcc.setExecuteId(executeId);
        this.save(bizAiNcc);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizAiNccEditParam bizAiNccEditParam) {
        BizAiNcc bizAiNcc = this.queryEntity(bizAiNccEditParam.getId());
        BeanUtil.copyProperties(bizAiNccEditParam, bizAiNcc);
        this.updateById(bizAiNcc);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizAiNccIdParam> bizAiNccIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizAiNccIdParamList, BizAiNccIdParam::getId));
    }

    @Override
    public BizAiNcc detail(BizAiNccIdParam bizAiNccIdParam) {
        return this.queryEntity(bizAiNccIdParam.getId());
    }

    @Override
    public BizAiNcc queryEntity(String id) {
        BizAiNcc bizAiNcc = this.getById(id);
        if(ObjectUtil.isEmpty(bizAiNcc)) {
            throw new CommonException("biz_ai_ncc不存在，id值为：{}", id);
        }
        return bizAiNcc;
    }

    @Override
    public List<BizAiNcc> queryCozeStatus() {
        LambdaQueryWrapper<BizAiNcc> lqw = new LambdaQueryWrapper<>();
        lqw.ne(BizAiNcc::getWorkFlowStatus, 1);
        return this.list(lqw);
    }

    @Override
    public void updateCozeStatus(String id, String res) {
        BizAiNcc aiNcc = this.getById(id);
        aiNcc.setWorkFlowStatus(1);
        aiNcc.setExtJson(res);
        this.updateById(aiNcc);
    }



    @Transactional(rollbackFor = Exception.class)
    @Async
    @Override
    public void createNccPay(BizAiNcc aiNcc) {
        String coze = aiNcc.getExtJson();
        if(coze == null || coze.isEmpty()) throw new RuntimeException("coze工作流数据执行错误");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            CozeResParam cozeRes = objectMapper.readValue(coze, CozeResParam.class);
            ConCustomerInfo conCustomerInfo = conCustomerInfoService.detail(cozeRes.getCvendor());
            if(conCustomerInfo == null) throw new RuntimeException("未查询到供应商信息，可能未在ncc系统中录入相应数据，请联系开发人员处理");
            NccClient nccClient = new NccClient(aiNcc.getNccUserCode());
            // 创建付款合同（查询关联Id）
            BizNccCode bizNccCode = bizNccCodeService.getByCode(aiNcc.getNccUserCode());
            ConExpenseParam conExpenseParam = new ConExpenseParam(aiNcc, conCustomerInfo.getNccCode(), bizNccCode.getNId());

            List<Map<String,String>> fa = initParam(cozeRes, aiNcc);
            List<Map<String,String>> fap = initParamPlan(cozeRes,aiNcc.getNccAdvancePay(), aiNcc.getNccOrg());

            conExpenseParam.setFct_ap_b(fa);
            conExpenseParam.setFct_ap_plan(fap);
            JSONObject res = nccClient.createConExpense(conExpenseParam, aiNcc.getNccUserCode());
            log.info("<创建合同接口>--------------接口请求响应结果：{}", res.toString());
            if(res.getBool("success") ){
                JSONArray data = res.getJSONArray("data");
                aiNcc.setNccConRes(data.toString());
                aiNcc.setNccConStatus("1");
            }else{
                String message = res.getStr("message");
                aiNcc.setNccConRes(res.toString());
                log.info("付款合同----NCC数据传输失败：{}, 传输网址为：{}", message, "创建付款合同");
            }
            aiNcc.setConNum(conCustomerInfo.getNccCode());
            aiNcc.setAmount(cozeRes.getAmount());
            aiNcc.setWorkFlowStatus(1);
            this.updateById(aiNcc);
        } catch (Exception e) {
            throw new RuntimeException("ncc接口<创建合同接口>调用失败，请检查调用方法，错误原因："+e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Async
    @Override
    public void createPayBill(BizAiNcc aiNcc){
        ObjectMapper objectMapper = new ObjectMapper();
        String conRes = aiNcc.getNccConRes();
        String coze = aiNcc.getExtJson();
        // 格式转化（获取单据创建的Id）
        try {
            CozeResParam cozeRes = objectMapper.readValue(coze, CozeResParam.class);
            List<JSONObject> list = JSON.parseArray(conRes, JSONObject.class);
            JSONObject object = list.get(0);
            JSONObject fctAb =  object.get("fct.fct_ap",JSONObject.class);
            JSONArray fctApBList =  object.get("fct.fct_ap_b",JSONArray.class);
            JSONObject object1 = (JSONObject) fctApBList.get(0);
            String topBillId =fctAb.getStr("pk_fct_ap");
            String topItemId = object1.getStr("pk_fct_ap_b");
            BizNccCode bizNccCode = bizNccCodeService.getByCode(aiNcc.getNccUserCode());
            JSONObject res = getPaymentRes(aiNcc, topBillId, topItemId, cozeRes.getCtName(), bizNccCode.getNId());
            log.info("<创建付款接口>--------------接口请求响应结果：{}", res.toString());
            aiNcc.setNccPayRes(res.toString());
            if (res.getBool("success") && null == res.getStr("successful")) {
                aiNcc.setNccPayStatus("1");
            } else {
                String message = res.getStr("message");
                log.info("付款单创建----NCC数据传输失败：{}, 传输网址为：{}", message, "创建付款单据");
            }
            aiNcc.setWorkFlowStatus(1);
            this.updateById(aiNcc);
        }catch (Exception e){
            throw new RuntimeException("ncc接口<创建付款接口>调用失败，请检查调用方法，错误原因："+e.getMessage());
        }

    }

    private static JSONObject getPaymentRes(BizAiNcc aiNcc, String topBillId, String topItemId, String comment, String userId) throws Exception {
        PaymentBillParam paymentBillParam = new PaymentBillParam(topBillId, topItemId, aiNcc.getConNum(), aiNcc.getAmount(), aiNcc.getFileSize().toString(),  userId, aiNcc.getNccOrg());
        PaymentItemParam paymentItemParam = new PaymentItemParam(aiNcc.getConNum(),aiNcc.getConNum(), aiNcc.getAmount(), comment, aiNcc.getNccMaterial(), aiNcc.getNccAccountType(), aiNcc.getNccOrg(), userId);
        List<PaymentItemParam> items = new ArrayList<>();
        items.add(paymentItemParam);
        paymentBillParam.setItems(items);
        NccClient nccClient = new NccClient();
        return nccClient.createPaymentBill(paymentBillParam, aiNcc.getNccUserCode());
    }

    /**
     * 静态方法，组装参数
     * @param cozeRes ai请求结果
     * @param aiNcc 单据对
     * @return
     */
    // 组织参数
    public static List<Map<String ,String>> initParam(CozeResParam cozeRes, BizAiNcc aiNcc){
        ArrayList<Map<String, String>> list = new ArrayList<>();
        Map<String, String> fctApb = new HashMap<>();
        fctApb.put("pk_financeorg", aiNcc.getNccOrg());
        fctApb.put("crowno", "10");
        fctApb.put("inoutcome", aiNcc.getNccAccountType());
        fctApb.put("norigtaxmny", cozeRes.getAmount());
        fctApb.put("ntaxmny",cozeRes.getAmount());
        list.add(fctApb);
        return list;
    }

    // 组织参数
    public static List<Map<String ,String>> initParamPlan(CozeResParam cozeRes, long isPay, String orgCode){
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        ArrayList<Map<String, String>> list = new ArrayList<>();
        Map<String, String> fctApbPlan = new HashMap<>();
        fctApbPlan.put("pk_financeorg", orgCode);
        fctApbPlan.put("begindate",sdf.format(now));
        fctApbPlan.put("enddate",sdf.format(now));
        fctApbPlan.put("accountdate","1");
        fctApbPlan.put("planrate","100.00");
        // 计划付款金额
        fctApbPlan.put("planmoney", cozeRes.getAmount());
        // 预付款
        if(isPay==1){
            fctApbPlan.put("paytype","Y");
        } else {
            fctApbPlan.put("paytype","N");
        }
        // 质保金
        fctApbPlan.put("moneytype","N");
        list.add(fctApbPlan);
        return list;
    }

    @Override
    public String checkPaymentBill() {
        PaymentBillSearchParam paymentBillParam = new PaymentBillSearchParam();
        NccClient nccClient = new NccClient();
        try {
            JSONObject res = nccClient.searchPaymentBill(paymentBillParam, "LW_002675");
            if(res.getBool("success") ){
                JSONArray data = res.getJSONArray("data");
                return data.toString();
            }else{
                return res.getStr("message");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用于文件的解压
     * 修改为异步处理
     * @param addParam
     */
    @Override
    @Async
    public void editBack(BizAiNccAddParam addParam) {
        List<String> fileIdList = addParam.getNccFileList();
        String unzipPath = FileUtil.getPath("unzip");
        String splitPath = FileUtil.getPath("split");
        try {
            for (String fileId : fileIdList) {
                JSONObject file = fileApi.getFileById(fileId);
                String filePath = file.get("storagePath").toString();
                UnzipUtil.extractZipFile(filePath, unzipPath);
            }
        }catch (Exception e){
            log.info("解压文件失败：{}",e.getMessage());
        }
        // 遍历文件，分隔文件
        try {
            Path dir = Paths.get(unzipPath);
            Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    log.info("开始识别文件：{}",file.getFileName());
                    System.out.println("File: " + file.toString()); // 输出文件路径
                    List<String> pathList = FileUtil.SplitPages(file.toString() ,splitPath, file.toFile().getName()); // 裁剪文件
                    if(pathList!= null){
                        for (int i = 0; i < pathList.size(); i++) {
                            try {
                                BizAiNcc bizAiNcc = new BizAiNcc();
                                bizAiNcc.setNccOrderType("回款单");
                                BankReceiptInfo info = FileUtil.readQRCodeFromPDF(pathList.get(i));
                                log.info("二维码解析结果：{}",info.toString());
                                if(info.getPayerName() == null) continue;
                                ObjectMapper objectMapper = new ObjectMapper();
                                bizAiNcc.setExecuteId(info.getTransactionDate());
                                bizAiNcc.setExtJson(objectMapper.writeValueAsString(info));
                                bizAiNcc.setConNum(info.getPayerName().replace(",",""));
                                bizAiNcc.setNccFileList(pathList.get(i));
                                save(bizAiNcc);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                    return FileVisitResult.CONTINUE; // 继续访问其他文件或目录
                }
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                    System.out.println("Directory: " + dir.toString()); // 输出目录路径（可选）
                    return FileVisitResult.CONTINUE; // 继续访问其他文件或目录
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询合同
     * @param
     * @return
     */
    @Override
    public List<BizAiNccIncomeConReturnParam> searchIncome( String vbillCode, String startDate, String endDate) {
        IncomeContractSearchParam searchParam = new IncomeContractSearchParam();
        List<String> ctNameList = new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        ctNameList.add(vbillCode);
        dateList.add(startDate);
        dateList.add(endDate);
        searchParam.setDmakedate(dateList);
        searchParam.setVbillcode(ctNameList);
        NccClient nccClient = new NccClient("004374");
        List<BizAiNccIncomeConReturnParam> resin = new ArrayList<>();

        try {
            nccClient.searchGatherBill();
            JSONObject res = nccClient.searchIncomeContract(searchParam,"004374");
            if(res.getBool("success") ){
                JSONArray data = res.getJSONArray("data");
                if(data == null) throw new CommonException("未查询到合同数据，无数据");
                data.forEach(item ->{
                    BizAiNccIncomeConReturnParam param = new BizAiNccIncomeConReturnParam();
                    JSONObject jsonObject = (JSONObject) item;
                    JSONObject fctAr = (JSONObject) jsonObject.get("fct.fct_ar");
                    JSONArray fctArb = jsonObject.getJSONArray("fct.fct_ar_b");
                    param.setCtName(fctAr.get("ctname").toString());
                    param.setFctPK(fctAr.get("pk_fct_ar").toString());
                    log.info("合同主键编号：{}",fctAr.get("pk_fct_ar"));
                    log.info("合同明细编号：{}",fctAr.get("pk_fct_ar"));
                    log.info("合同名称：{}",fctAr.get("ctname"));
                    List<String> paList = new ArrayList<>();
                    fctArb.forEach(j ->{
                        JSONObject jsonObject1 = (JSONObject) j;
                        paList.add(jsonObject1.get("pk_fct_ar_b").toString());
                        log.info("合同明细编号：{}",jsonObject1.get("pk_fct_ar_b"));
                    });
                    param.setFctPKARbList(paList);
                    resin.add(param);
                });
            }else{
                return null;
            }
           return resin;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建ncc收款单
     * @return
     */
    @Override
    public String createGatherBill(List<String> nccKeyList, String fcArPk,  List<String> fcArPkBList, String contractNo, String material) {
        NccClient nccClient = new NccClient();
        List<BizAiNcc> nccList = listByIds(nccKeyList);
        Map<String, List<BizAiNcc>> groupedByDate = nccList.stream()
                .collect(Collectors.groupingBy(BizAiNcc::getExecuteId));
        groupedByDate.forEach((key, value) -> {
            GatherBillAddParam addParam = new GatherBillAddParam("004374", key);
            addParam.setTop_billid(fcArPk);
            addParam.setSrc_billid(fcArPk);
            addParam.setTop_itemid(fcArPkBList.get(0));
            addParam.setSrc_itemid(fcArPkBList.get(0));
            List<GatherBillItemParam> itemParamList = new ArrayList<>();
            BigDecimal amount = BigDecimal.ZERO;
            List<String> waitFileList = new ArrayList<>();
            for (int i = 0; i < value.size(); i++) {
                String query = value.get(i).getExtJson();
                BankReceiptInfo bankReceiptInfo = JSONUtil.toBean(query, BankReceiptInfo.class);
                GatherBillItemParam itemParam = new GatherBillItemParam(material);
                String customer = bankReceiptInfo.getPayerName();
                ConCustomerInfo conCustomerInfo = conCustomerInfoService.detailOwner(customer.replaceAll("^,+|,+$", ""));
                if(conCustomerInfo == null) throw new CommonException("客户不存在");
                // itemParam.setSupplier(conCustomerInfo.getNccId());
                itemParam.setTop_billid(fcArPk);
                itemParam.setSrc_billid(fcArPk);
                itemParam.setTop_itemid(fcArPkBList.get(0));
                itemParam.setSrc_itemid(fcArPkBList.get(0));
                itemParam.setOrdercubasdoc(conCustomerInfo.getNccId());
                itemParam.setMatcustcode(conCustomerInfo.getNccId());
                itemParam.setCustomer(conCustomerInfo.getNccId());
                addParam.setCustomer(conCustomerInfo.getNccId());
                addParam.setCustomer_name(conCustomerInfo.getCustomerName());
                addParam.setCustomer_code(conCustomerInfo.getNccCode());
                String scomment = "收" + bankReceiptInfo.getPayerName().replaceAll("^,+|,+$", "") + "钢材货款"+i;
                // 原币
                itemParam.setMoney_cr(bankReceiptInfo.getAmount().toString());
                itemParam.setLocal_money_cr(bankReceiptInfo.getAmount().toString());
                itemParam.setOccupationmny(bankReceiptInfo.getAmount().toString());
                itemParam.setLocal_money_bal(bankReceiptInfo.getAmount().toString());


                // itemParam.setGrouprate(bankReceiptInfo.getAmount().toString());
                BigDecimal noTaxCr = bankReceiptInfo.getAmount().multiply(new BigDecimal(0.87));
                itemParam.setNotax_cr(noTaxCr.setScale(2, RoundingMode.HALF_UP).toString());
                itemParam.setLocal_notax_cr(noTaxCr.setScale(2, RoundingMode.HALF_UP).toString());
                BigDecimal taxCr = bankReceiptInfo.getAmount().multiply(new BigDecimal(0.13));
                itemParam.setLocal_tax_cr(taxCr.setScale(2, RoundingMode.HALF_UP).toString());
                itemParam.setScomment(scomment);

                itemParam.setDef65(bankReceiptInfo.getAmount().toString());
                // itemParam.setMoney_bal(bankReceiptInfo.getAmount().toString());
                itemParam.setContractno(contractNo);
                itemParamList.add(itemParam);
                amount = amount.add(bankReceiptInfo.getAmount());
                waitFileList.add(value.get(i).getNccFileList());
            }
           /* for (BizAiNcc aiNcc : value) {

            }*/
            addParam.setMoney(amount.toString());
            addParam.setLocal_money(amount.toString());
            addParam.setItems(itemParamList);
            addParam.setAccessorynum(Integer.toString(nccKeyList.size()));
            try {
                JSONObject res = nccClient.createGatherBill(addParam,"004374");
                if(res.getBool("success") ){
                    JSONObject data = (JSONObject) res.get("data");
                   /* for (int i = 0; i < waitFileList.size(); i++) {
                        String filePath = waitFileList.get(i);
                        File file = new File(filePath);
                        long timestamp = System.currentTimeMillis();
                        String fileName = "ncc回款单附件"+i+timestamp+".pdf";
                        // 推送ncc回款单到ncc系统
                        String url = "http://117.157.233.239:8077/imageUploadServices/uploadDocument";
                        Integer state = nccClient.uploadNccFile(filePath, fileName, data.get("pk_bill").toString(), url);
                        if(state == 2) throw new RuntimeException("影像上传失败");
                    }*/
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return null;
    }

    @Override
    public Map<String, List<String>> getNccOptions() {
        Map<String, List<String>> map = new HashMap<>();
        List<BizAiNcc> list = this.list();
        Map<String, List<BizAiNcc>> dateGroup = list.stream().collect(Collectors.groupingBy(BizAiNcc::getExecuteId));
        Map<String, List<BizAiNcc>> nameGroup = list.stream().collect(Collectors.groupingBy(BizAiNcc::getConNum));
        /* map.put("dateList", dateList);
        map.put("nameList", nameList);*/
        List<String> date = new ArrayList<>(dateGroup.keySet());
        List<String> name = new ArrayList<>(nameGroup.keySet());
        map.put("dateList", date);
        map.put("nameList", name);
        return map;
    }

    @Override
    public void getFilesList(List<String> nccKeyList, HttpServletResponse response) {
        List<BizAiNcc> nccList = listByIds(nccKeyList);
        // List<String> fileList = nccList.stream().map(BizAiNcc::getNccFileList).collect(Collectors.toList());
        // 生成临时目录
        File tempFolder = cn.hutool.core.io.FileUtil.file(cn.hutool.core.io.FileUtil.getTmpDirPath() + File.separator + "银行流水单据");
        try {
            for (int i = 0; i < nccList.size(); i++) {
                String filePath = nccList.get(i).getNccFileList();
                // 读取客户信息
                ObjectMapper objectMapper = new ObjectMapper();
                BankReceiptInfo info = objectMapper.readValue(nccList.get(i).getExtJson(), BankReceiptInfo.class);
                File newFile = new File(tempFolder, info.getPayerName().replaceAll("^,+|,+$", "")+i+ ".pdf");
                File oldFile = new File(filePath);
                cn.hutool.core.io.FileUtil.copyFile(oldFile, newFile);
            }
            // 压缩
            File zip = ZipUtil.zip(tempFolder);
            // 压缩完毕删除临时目录
            cn.hutool.core.io.FileUtil.del(tempFolder);
            // 下载
            CommonDownloadUtil.download(zip, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
/*

        // 生成临时目录
        File tempFolder = cn.hutool.core.io.FileUtil.file(cn.hutool.core.io.FileUtil.getTmpDirPath() + File.separator + "银行流水单据");
        // 移动文件到临时目录
        for (String filePath : fileList) {
            File sourceFile = new File(filePath);
            File destFile = new File(tempFolder, sourceFile.getName());
            cn.hutool.core.io.FileUtil.copyFile(sourceFile, destFile);
        }
        // 压缩
        File zip = ZipUtil.zip(tempFolder);
        // 压缩完毕删除临时目录
        cn.hutool.core.io.FileUtil.del(tempFolder);
        // 下载
        CommonDownloadUtil.download(zip, response);*/
    }
}
